package think.in.java.concurrency.PractiseOneMoreTime;

import java.util.Iterator;

/**
 * Created by richard on 5/1/14.
 */
public class IteratorFibonacci implements Iterable<Integer> {
    private int iterateTimes ;
    private Fibonacci fibonacci;

    public IteratorFibonacci(Integer iterateTimes){
        this.iterateTimes = iterateTimes;
        fibonacci = new Fibonacci();
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            @Override
            public boolean hasNext() {
                return iterateTimes>0;
            }

            @Override
            public Integer next() {
                iterateTimes--;
                return fibonacci.getFibonacci();
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };

    }


}

class Fibonacci{
    private Integer previousValue=0;
    private Integer currentValue=0;
    public Integer getFibonacci(){
        if(currentValue == 0){
            currentValue =1;
            return currentValue;
        }
        if(previousValue==0){
            previousValue=currentValue;
            return currentValue;
        }
        return currentValue = currentValue + previousValue;
    }
}
